package com.gudaichaoren.spider.pipeline;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gudaichaoren.spider.constant.Constants;
import com.gudaichaoren.spider.entity.LotteriesShuangseAnalysis;
import com.gudaichaoren.spider.entity.LotteriesShuangseResults;
import com.gudaichaoren.spider.mapper.LotteriesShuangseAnalysisMapper;
import com.gudaichaoren.spider.mapper.LotteriesShuangseResultsMapper;
import com.gudaichaoren.spider.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import javax.annotation.Resource;
import java.util.ArrayList;

@Component
public class LotteriesShuangsePipeline implements Pipeline {

    @Resource
    private LotteriesShuangseResultsMapper lotteriesShuangseResultsMapper;

    @Autowired
    private LotteriesShuangseAnalysisMapper lotteriesShuangseAnalysisMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void process(ResultItems resultItems, Task task) {
        //保存完整页面到redis
        redisUtil.set(Constants.RedisConstant.INTEGRAL_HTML, resultItems.get("integralHtml"));
        /**保存彩票_双色球开奖结果
         *
         */
        ArrayList<LotteriesShuangseResults> lotteriesShuangseResultsList = resultItems.get("lotteriesShuangseResultsList");
        for (LotteriesShuangseResults lotteriesShuangseResults : lotteriesShuangseResultsList) {
            if (lotteriesShuangseResultsMapper.selectCount(new QueryWrapper<LotteriesShuangseResults>().eq("period", lotteriesShuangseResults.getPeriod())) == 0) {
                //新增
                lotteriesShuangseResultsMapper.insert(lotteriesShuangseResults);
            }
        }
        /**彩票_双色球分析数据
         *
         */
        ArrayList<LotteriesShuangseAnalysis> lotteriesShuangseAnalysisList = resultItems.get("lotteriesShuangseAnalysisList");
        for (LotteriesShuangseAnalysis lotteriesShuangseAnalysis : lotteriesShuangseAnalysisList) {
            LotteriesShuangseAnalysis shuangseAnalysis = lotteriesShuangseAnalysisMapper.selectOne(new QueryWrapper<LotteriesShuangseAnalysis>().eq("analysis_type", lotteriesShuangseAnalysis.getAnalysisType()));
            if (shuangseAnalysis == null) {
                //新增
                lotteriesShuangseAnalysisMapper.insert(lotteriesShuangseAnalysis);
            } else {
                //更新
                lotteriesShuangseAnalysisMapper.update(lotteriesShuangseAnalysis, new UpdateWrapper<LotteriesShuangseAnalysis>().eq("analysis_type", lotteriesShuangseAnalysis.getAnalysisType()));
            }
        }
    }
}
